package software.literature.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import software.literature.model.bean.Literature;
import software.literature.view.treeitem.LiteratureTreeItem;

public class LiteratureDao extends DBDao{
	public  LiteratureDao(String currentDB){
		super(currentDB);
	}
	public boolean insertLiterature(LiteratureTreeItem lite) {
		// TODO Auto-generated method stub
		try {
			getConnection();
			preStm=connection.prepareStatement("insert into literature(name) values(?)");
			preStm.setString(1, lite.getText());
			int re=preStm.executeUpdate();
			preStm=connection.prepareStatement("select max(id) from literature");
			result=preStm.executeQuery();
			if(result.next()){
				lite.setId(result.getInt(1));
			}
			closeConnection();
			if(1==re){
				return true;
			}else{
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false; 
	}
	public boolean updateName(int id, String name) {
		// TODO Auto-generated method stub
				try {
					getConnection();
					preStm=connection.prepareStatement("update  literature set name=? where id=?");
					preStm.setString(1, name);
					preStm.setInt(2, id);
					int re=preStm.executeUpdate();
					closeConnection();
					if(1==re){
						return true;
					}else{
						return false;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false; 
		
	}
	//the Literature id and it's data
	public Map<Integer, Literature> queryData() {
		System.out.println("queryData start");
		Map<Integer, Literature> itemsMap = new HashMap<Integer, Literature>();
		try {
			getConnection();
			preStm=connection.prepareStatement("select * from  literature ");
			result = preStm.executeQuery();
			Literature item;
			while (result.next()) {
				item = new Literature();
				item.setId(result.getInt("id"));
				item.setName(result.getString("name"));
				itemsMap.put(item.getId(), item);
			}
			closeConnection();
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("queryData end");
		return itemsMap;
		// TODO Auto-generated method stub
	}
	public boolean deleteLiterature(int id) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
				try {
					getConnection();
					preStm=connection.prepareStatement("delete from literature where id=?");
					preStm.setInt(1, id);
					int re=preStm.executeUpdate();
					closeConnection();
					if(1==re){
						return true;
					}else{
						return false;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return false; 
	}
}
